#include "message.h"
#include <iterator>
#include "DataTypes.h"

Data Message::getMsgBytes() const
{
    Data retval;
    //header
    retval = header_.getRawBytes();
    //payload
    retval.insert(retval.end(), payload_.begin(),payload_.end());
    //checksum
    retval.push_back(getChecksum());
    return retval;

}

const Data& Message::getPayload() const
{
    return payload_;
}
void  Message::setAddresses(PartiesAddresses addr)
{
    header_.setAddress(addr);
    calculateChecksum();
}
void  Message::setPayload(const Data& payload)
{
    payload_ = payload;
    calculateChecksum();
}
void  Message::addHeader(bool isTwoByteHeaderSupported)
{
    header_.setTwoByteHeaderAvaliable(isTwoByteHeaderSupported);
    header_.setMessageLength(payload_.size() + 1);//PAYLOAD+checksum
    calculateChecksum();
}
char Message::getChecksum() const
{
    unsigned char checksum(0);
    Data header = header_.getRawBytes();
    for(Data::const_iterator i=header.begin();i!=header.end();++i)
        checksum+=*i;
    for(Data::const_iterator i = payload_.begin();i!=payload_.end();++i)
        checksum+=*i;
    return checksum;

}
char Message::calculateChecksum()
{
    unsigned char checksum(0);
    Data header = header_.getRawBytes();
    for(Data::iterator i=header.begin();i!=header.end();++i)
        checksum+=*i;
    for(Data::iterator i = payload_.begin();i!=payload_.end();++i)
        checksum+=*i;
    checksum_ = checksum;
    return checksum;
}
